const fs = require("fs");
const path = require("path");
const { clipboard, nativeImage } = require("electron");

// uTools 插件入口
utools.onPluginEnter(({ code, type, payload }) => {
    console.log('插件进入', code, type, payload);
});

// 导出功能函数
module.exports = {
    // 保存图片到剪贴板
    copyImageToClipboard(imageDataUrl) {
        try {
            const data = imageDataUrl.replace(/^data:image\/\w+;base64,/, "");
            const buf = Buffer.from(data, 'base64');
            const image = nativeImage.createFromBuffer(buf);
            clipboard.writeImage(image);
            return { success: true, message: '图片已复制到剪贴板' };
        } catch (error) {
            console.error('复制图片失败:', error);
            return { success: false, message: '复制失败: ' + error.message };
        }
    },
    
    // 保存图片到文件
    saveImageToFile(imageDataUrl, fileName) {
        try {
            const data = imageDataUrl.replace(/^data:image\/\w+;base64,/, "");
            const buf = Buffer.from(data, 'base64');
            
            // 使用uTools的文件保存对话框
            const savePath = utools.showSaveDialog({
                title: '保存图片',
                defaultPath: fileName,
                filters: [
                    { name: 'PNG Images', extensions: ['png'] },
                    { name: 'JPEG Images', extensions: ['jpg', 'jpeg'] },
                    { name: 'WebP Images', extensions: ['webp'] },
                    { name: 'All Files', extensions: ['*'] }
                ]
            });
            
            if (savePath) {
                fs.writeFileSync(savePath, buf);
                return { success: true, message: '图片保存成功', path: savePath };
            } else {
                return { success: false, message: '用户取消保存' };
            }
        } catch (error) {
            console.error('保存图片失败:', error);
            return { success: false, message: '保存失败: ' + error.message };
        }
    },
    
    // 获取系统信息
    getSystemInfo() {
        return {
            platform: process.platform,
            arch: process.arch,
            version: process.version
        };
    }
};
